// src/main.ts
import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import * as express from 'express'
import { logger } from './middleware/logger.middleware'
import { TransformInterceptor } from './interceptor/transform.interceptor'
import { HttpExceptionFilter } from './filter/http-exception.filter'
import { AllExceptionsFilter } from './filter/any-exception.filter'
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'
import { ConfigService } from './config/config.service'
import * as helmet from 'helmet'
import * as csurf from 'csurf'
import * as compression from 'compression'
import * as rateLimit from 'express-rate-limit'
async function bootstrap() {
    const app = await NestFactory.create(AppModule)
    // 获取配置
    const config: ConfigService = app.get(ConfigService)
    app.use(express.json()) // For parsing application/json
    app.use(express.urlencoded({ extended: true })) // For parsing application/x-www-form-urlencoded
    // 监听所有的请求路由，并打印日志
    app.use(logger)

    // 使用拦截器打印出参
    app.useGlobalInterceptors(new TransformInterceptor())
    app.setGlobalPrefix('api')
    app.useGlobalFilters(new AllExceptionsFilter())
    app.useGlobalFilters(new HttpExceptionFilter())
    // 配置 Swagger
    const options = new DocumentBuilder()
        .addBearerAuth() // 开启 BearerAuth 授权认证
        .setTitle('Nest zero to one')
        .setDescription('The nest-zero-to-one API description')
        .setVersion('1.0')
        .addTag('test')
        .build()
    const document = SwaggerModule.createDocument(app, options)
    SwaggerModule.setup('api-doc', app, document)
    app.use(
        helmet({
            frameguard: false // 是否拦截iframe嵌套页面请求
            // frameguard: {    // iframe嵌套页面请求白名单模式
            //     action: 'allow-from',
            //     domain: 'data-monitoring.annoak.com',
            // },
        })
    )
    app.use(
        rateLimit({
            windowMs: 15 * 60 * 1000, // 15 minutes
            max: 100 // limit each IP to 100 requests per windowMs
        })
    )
    // somewhere in your initialization file
    app.use(compression())
    // app.use(csurf({ cookie: true }))
    app.enableCors()
    await app.listen(config.getNumber('PORT'))
}
bootstrap()
